package com.bjtu.ptsite.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bjtu.ptsite.exception.InsufficientPointsException;
import com.bjtu.ptsite.exception.UserNotFoundException;
import com.bjtu.ptsite.mapper.UserMapper;
import com.bjtu.ptsite.model.User;
import com.bjtu.ptsite.service.PointsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author Zehao Wang, Junjie Zhang, Yutao Wei
 *
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class PointsServiceImpl implements PointsService {
    private final UserMapper userMapper;
    private static final int POINTS_PER_GB = 100;

    @Autowired
    public PointsServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public void exchangePoints(int userId, int points)
            throws InsufficientPointsException, UserNotFoundException {

        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new UserNotFoundException("用户不存在");
        }

        if (user.getSeedPoints() < points) {
            throw new InsufficientPointsException("可用积分不足");
        }

        long uploadDelta = (long)(points / POINTS_PER_GB)*(long)Math.pow(2, 30);
        User updateUser = userMapper.selectById(userId);
        updateUser.setSeedPoints(user.getSeedPoints() - points);
        updateUser.setUploadedDelta(user.getUploadedDelta() + uploadDelta);
        userMapper.updateUserSelective(updateUser);
    }

    @Override
    public void receivePoints(int userId, int points)
            throws UserNotFoundException {

        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new UserNotFoundException("用户不存在");
        }

        user.setSeedPoints(user.getSeedPoints() + points);
        userMapper.updateUserPoints(user);
    }

    @Override
    public void deductPoints(int userId, int points)  {//扣除一定积分

        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new UserNotFoundException("用户不存在");
        }

        if (user.getSeedPoints() < points) {
            throw new InsufficientPointsException("可用积分不足");
        }

        User updateUser = userMapper.selectById(userId);
        updateUser.setSeedPoints(user.getSeedPoints() - points);
        userMapper.updateUserSelective(updateUser);
    }
}